import os
import time
import subprocess
import requests
from urllib.parse import urlparse
import json

class FiddlerController:
    def __init__(self, fiddler_exe_path=None):
        """初始化 Fiddler 控制器"""
        self.fiddler_exe_path = fiddler_exe_path or r"C:\Users\Admin\AppData\Local\Programs\Fiddler\Fiddler.exe"
        self.fiddler_process = None
        self.proxy_port = 8888  # Fiddler 默认代理端口
        self.fiddler_api_base = f"http://localhost:{self.proxy_port}/__msgbox"
        
    def start_fiddler(self):
        """启动 Fiddler 进程"""
        if not os.path.exists(self.fiddler_exe_path):
            raise FileNotFoundError(f"未找到 Fiddler 可执行文件: {self.fiddler_exe_path}")
        
        print("正在启动 Fiddler...")
        self.fiddler_process = subprocess.Popen(
            [self.fiddler_exe_path], 
            stdout=subprocess.PIPE, 
            stderr=subprocess.PIPE
        )
        
        # 等待 Fiddler 启动
        time.sleep(5)
        print("Fiddler 已启动")
        
    def stop_fiddler(self):
        """停止 Fiddler 进程"""
        if self.fiddler_process:
            print("正在关闭 Fiddler...")
            self.fiddler_process.terminate()
            self.fiddler_process.wait()
            print("Fiddler 已关闭")
            
    def clear_sessions(self):
        """清除 Fiddler 当前会话"""
        try:
            requests.get(f"{self.fiddler_api_base}/ClearSessions")
            print("已清除 Fiddler 会话")
        except Exception as e:
            print(f"清除会话失败: {e}")
            
    def capture_url(self, url):
        """使用 Fiddler 捕获指定 URL 的请求"""
        # 解析 URL 获取主机和端口
        parsed_url = urlparse(url)
        host = parsed_url.hostname
        port = parsed_url.port or (443 if parsed_url.scheme == 'https' else 80)
        
        # 设置请求头
        headers = {
            'Host': host,
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
            'Connection': 'keep-alive'
        }
        
        # 配置代理
        proxies = {
            'http': f'http://localhost:{self.proxy_port}',
            'https': f'http://localhost:{self.proxy_port}'
        }
        
        print(f"正在访问 URL: {url}")
        try:
            # 发送请求并获取响应
            response = requests.get(url, headers=headers, proxies=proxies, verify=False, timeout=10)
            print(f"请求完成，状态码: {response.status_code}")
            return response
        except Exception as e:
            print(f"请求失败: {e}")
            return None
            
    def get_sessions(self):
        """获取 Fiddler 捕获的会话信息"""
        try:
            # 获取所有会话
            response = requests.get(f"{self.fiddler_api_base}/GetAllSessions")
            sessions = json.loads(response.text)
            
            # 解析会话信息
            results = []
            for session in sessions:
                req = session.get('request', {})
                resp = session.get('response', {})
                
                info = {
                    'id': session.get('id'),
                    'method': req.get('method'),
                    'url': req.get('url'),
                    'status': resp.get('status'),
                    'content_type': resp.get('headers', {}).get('Content-Type'),
                    'body_size': len(resp.get('body', ''))
                }
                results.append(info)
                
            return results
        except Exception as e:
            print(f"获取会话信息失败: {e}")
            return []

def main():
    """主函数，程序入口点"""
    # 创建 Fiddler 控制器实例
    fiddler = FiddlerController()
    
    try:
        # 启动 Fiddler
        fiddler.start_fiddler()
        
        # 清除现有会话
        fiddler.clear_sessions()
        
        # 获取用户输入的 URL
        target_url = "http://novel.hctestedu.com/"
        
        # if not target_url:
        #     print("未输入网址，使用默认测试网址")
        #     target_url = "https://httpbin.org/get"
            
        # 捕获 URL
        fiddler.capture_url(target_url)
        
        # 等待一段时间，确保捕获完成
        time.sleep(2)
        
        # 获取会话信息
        sessions = fiddler.get_sessions()
        
        if sessions:
            print("\n捕获到的接口信息:")
            print("=" * 60)
            print(f"{'ID':<5} {'Method':<7} {'Status':<8} {'Size(KB)':<10} {'URL'}")
            print("-" * 60)
            
            for session in sessions:
                print(f"{session['id']:<5} {session['method']:<7} {session['status']:<8} "
                      f"{session['body_size']/1024:0.2f}KB  {session['url'][:70]}")
            print("=" * 60)
            print(f"共捕获 {len(sessions)} 个接口")
        else:
            print("未捕获到任何接口信息")
            
    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        # 停止 Fiddler
        fiddler.stop_fiddler()

if __name__ == "__main__":
    main()